package com.masc.gurr.model;

import java.util.ArrayList;
import java.util.HashMap;

public class History {
	
	public static final short TYPE_CURRENT=0x0;
	public static final short TYPE_PAST=0x1;
	public static final short TYPE_BUFFER=0x2;
	
	private short fShortType;
	private long fLongFreeSid;
	private String fStrUin;
	private HashMap<String, ArrayList<Session>> fMapBuddyUinSessions;
	
	public History(short pIntType, String pStrUin) {
		fShortType=pIntType;
		fStrUin=pStrUin;
		fMapBuddyUinSessions=new HashMap<String, ArrayList<Session>>();
	}
	
	public Session addSession(String pStrBuddyUin, String pStrMyUin, ProtocolType pProtocolType) {
		Session s = new Session(pStrBuddyUin, this, pStrMyUin, pProtocolType, fLongFreeSid);
		fLongFreeSid++;
		if (! fMapBuddyUinSessions.containsKey(pStrBuddyUin))
			fMapBuddyUinSessions.put(pStrBuddyUin, new ArrayList<Session>());
		fMapBuddyUinSessions.get(pStrBuddyUin).add(s);
		return s;
	}
	
	public Session addSession(String pStrBuddyUin, String pStrMyUin, ProtocolType pProtocolType, long pLongSid) {
		Session s = new Session(pStrBuddyUin, this, pStrMyUin, pProtocolType, pLongSid);
		if (! fMapBuddyUinSessions.containsKey(pStrBuddyUin))
			fMapBuddyUinSessions.put(pStrBuddyUin, new ArrayList<Session>());
		fMapBuddyUinSessions.get(pStrBuddyUin).add(s);
		return s;
	}
	
	public void removeSession(Session pSession) {
		pSession.setParentHistory(null);
		if (! fMapBuddyUinSessions.containsKey(pSession.getBuddyUin()))
			return;
		fMapBuddyUinSessions.get(pSession.getBuddyUin()).remove(pSession);
		if ( fMapBuddyUinSessions.get(pSession.getBuddyUin()).isEmpty() )
			fMapBuddyUinSessions.remove(pSession.getBuddyUin());
		
	}
	
	public boolean hasSession(String pStrUin) {
		return fMapBuddyUinSessions.containsKey(pStrUin);
	}
	
	public HashMap<String, ArrayList<Session>> getBuddyUinSessionMap() {
		return fMapBuddyUinSessions;
	}
	
	
	public short getType() {
		return fShortType;
	}
	
	public long getFreeSid() {
		return fLongFreeSid;
	}
	
	public void setFreeSid(long pLongFreeSid) {
		fLongFreeSid = pLongFreeSid;
	}
	
	public String getMyUin() {
		return fStrUin;
	}
	
	public void setMyUin(String pStrMyUin) {
		fStrUin=pStrMyUin;
	}

	public void removeAllSessions() {
		fMapBuddyUinSessions.clear();
	}

	public void removeAllSessions(String pStrBuddyUin) {
		if (! fMapBuddyUinSessions.containsKey(pStrBuddyUin))
			return;
		ArrayList<Session> sessions = fMapBuddyUinSessions.get(pStrBuddyUin);
		for (Session s : sessions) {
			removeSession(s);
		}
	}
	
}
